<template>
  <el-dialog class="assign-role" title="分配角色" :visible="showRoleDialog" :close-on-click-modal="false" @open="openDialog" @close="closeRoleDialog">
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button type="primary" size="small" @click="btnOK">确定</el-button>
      <el-button size="small" @click="closeRoleDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getRoleListApi } from '@/api/setting'
import { getUserIconApi } from '@/api/user'
import { editRoleApi } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 角色id
      checkList: [],
      data: {
        page: 1,
        pagesize: 10000000
      },
      // 角色列表
      list: [],
      // loading
      loading: false
    }
  },
  created() {
    this.getRoleInfo()
  },
  methods: {
    openDialog() {
      this.loading = true
      // Promise.all 可以存在所有的异步代码
      Promise.all([
        this.getRoleInfo(),
        this.roleShow()
      ]).then(() => {
        this.loading = false
      })
    },
    // 关闭弹框
    closeRoleDialog() {
      this.$emit('update:showRoleDialog', false)
    },
    // 获取角色信息
    async getRoleInfo() {
      const { data: res } = await getRoleListApi(this.data)
      this.list = res.rows
    },
    // 信息回显
    async roleShow() {
      const res = await getUserIconApi(this.userId)
      // console.log(res)
      this.checkList = res.data.roleIds || []
    },
    // 分配员工角色
    async btnOK() {
      await editRoleApi({ id: this.userId, roleIds: this.checkList })
      this.$message.success('更新成功')
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>
